// 操作数库的对象  db
// 数据库：blog_database
// 数据表：pre_article

// SELECT  字段
// FROM  数据表
// WHERE  条件
// INSERT  INTO 插入
// INTO   数据表
// UPDATE   数据表  更新
// DELETE   删除  
// DELETE FROM 数据表

const db = require("../common/db/index")

module.exports = {
    // 发布文章
    publish(title, author, cate, cate_name, content, src, tag, createAt) {
        return new Promise(async (resolve, reject) => {
            const sql = 'SELECT title FROM pre_article WHERE title = ?';
            const rows = await db.query(sql, [title]);
            if (rows.length == 0) {
                // 尚未存在
                const sql2 = 'INSERT INTO pre_article (title, author, cate, cate_name, content, src, tag, createAt) VALUES (?, ?, ?,?, ?,?,?,?)';
                await db.query(sql2, [title, author, cate, cate_name, content, src, tag, createAt])
                    .then(
                        result => {
                            resolve({
                                msg: "发布文章成功",
                                code: 200,
                                result: result
                            })
                        },
                        err => {
                            reject({
                                msg: "发布文章失败",
                                code: 500,
                                err: err
                            })
                        }
                    )
            }
            else {
                // 已存在
                resolve({
                    msg: "文章已经发布",
                    code: 1
                })
            }


        })
    },
    // 获取所有的文章
    list() {
        return new Promise(async (resolve, reject) => {
            const rows = await db.query(`SELECT count(*) as total FROM pre_article`);
            const sql = 'SELECT * FROM pre_article'
            await db.query(sql)
                .then(
                    result => {
                        resolve({
                            total: rows[0].total,
                            result,
                            msg: "获取文章列表成功",
                            code: 200
                        })
                    },
                    err => {
                        reject({
                            err,
                            msg: "获取数据失败",
                            code: -1
                        })
                    }
                )
        })
    },

    // 文章列表
    items(page_num, page_size) {
        return new Promise(async (resolve, reject) => {
            // 编写sql语句 （查询语句）
            // 页码：第几页
            // 数量: 每一页的数量
            // 编写sql语句（更新数据）
            // ? 占位符  和[ ]的参数顺序是一一对应的
            const rows = await db.query(`SELECT count(*) as total FROM pre_article`);
            // 换种写法
            // 写法2：
            let page_num2 = ((parseInt(page_num) - 1) * parseInt(page_size))
            let page_size2 = (parseInt(page_size))
            let sql = `select * from pre_article limit ${page_num2} , ${page_size2}`
            await db.query(sql)
                .then(
                    data => {
                        resolve({
                            total: rows[0].total,
                            data,
                            msg: "获取文章列表成功",
                            code: 200
                        })
                    },
                    err => {
                        reject({
                            err,
                            msg: "获取数据失败"
                        })
                    }
                )

        })
    },

    // 删除文章
    remove(id) {
        return new Promise((resolve, reject) => {
            // 编写sql语句（更新数据）
            // ? 占位符  和[ ]的参数顺序是一一对应的
            const sql = 'DELETE FROM pre_article WHERE id = ?';
            db.query(sql, [id])
                .then(
                    result => {
                        resolve({
                            code: 200,
                            msg: "删除文章成功",
                            result
                        })
                    },
                    err => {
                        reject({
                            code: -1,
                            err
                        })
                    }
                )

        })
    },

    // 搜索文章
    search(keyword) {
        return new Promise((resolve, reject) => {
            // 编写sql语句（模糊查询）
            const sql = 'SELECT * FROM pre_article WHERE title LIKE ? or author LIKE ? or cate_name LIKE ? or cate LIKE ?';
            db.query(sql, [`%${keyword}%`, `%${keyword}%`, `%${keyword}%`, `%${keyword}%`])
                .then(
                    result => {
                        if (result.length > 0) {
                            resolve({
                                code: 200,
                                result,
                                msg: "搜索文章成功"
                            })
                        } else {
                            resolve({
                                code: -1,
                                msg: "没有搜索到结果",
                                result
                            })
                        }
                    },
                    err => {
                        reject({
                            code: -1,
                            msg: "搜索文章失败",
                            err: err
                        })
                    }
                )
        })
    },

    // 查看文章详情
    detail(id) {
        return new Promise((resolve, reject) => {
            // 编写sql语句 （查询语句）
            const sql = 'SELECT * FROM pre_article WHERE id = ?';
            // 通过query方法执行sql语句
            db.query(sql, [Number(id)])
                .then(
                    result => {
                        resolve(result)
                    },
                    err => {
                        reject(err)
                    }
                )

        })
    },

    // 修改文章
    modify(title, author, cate, cate_name, content, src, tag, id) {
        return new Promise((resolve, reject) => {
            // 编写sql语句（更新数据）
            // title, author, cate, cate_name, content, src, tag
            const sql = 'UPDATE pre_article SET title = ?, author = ? , cate = ?, cate_name = ?, content = ?, src = ?, tag = ? WHERE id = ?';
            db.query(sql, [title, author, cate, cate_name, content, src, tag, id])
                .then(
                    result => {
                        resolve({
                            result,
                            msg: "修改文章成功"
                        })
                    },
                    err => {
                        reject(err)
                    }
                )

        })
    },
}